<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="/statics/css/index.css"/>
</head>
<body>
<div class="fixed-background">
</div>
<div id="app">
    <el-container>
        <el-header style="height:50px;">
            <div class="header">
                <el-image style="width: 45px; height: 45px;margin-right: 10px" :src="personInfo.avatar"></el-image>
                <span class="el-dropdown-link"
                      style="line-height:45px;font-weight: bold;margin-right: 10px;font-size:20px ">
                            {{personInfo.nickname}}
                </span>
                <ul>
                    <li @click="toPersonInfo">个人信息</li>
                    <li @click="toggleChangePassword">修改密码</li>
                    <li @click="toggleStatus(1)">发布新内容</li>
                    <li @click="logout">退出</li>

                </ul>
            </div>
            <el-col :span="8" :offset="8">
                <el-input placeholder="请输入内容" v-model="key">
                    <i slot="suffix" class="el-input__icon el-icon-search"
                       @click="search"></i>
                </el-input>
            </el-col>
        </el-header>
        <el-main>
            <el-container>
                <el-main>
                    <el-row v-infinite-scroll="load" class="infinite-list custom-scroll" style="overflow:auto;">
                        <el-col :span="6" :offset="2"
                                v-for="(blog,index) in blogs" :key="blog.id"
                                class="infinite-list-item">
                            <el-card @click.native="blogDetail(blog.blogId)">
                                <h4>{{blog.title}}</h4>
                                <section style="display: flex;flex-direction: row-reverse">
                                        <span>
                                            <i class="el-icon-view"></i>
                                            {{blog.readed}}
                                        </span>
                                    <span class="date">{{blog.createDate | dateFormate}}</span>
                                    <span class="author">{{blog.authorName}}</span>
                                </section>
                                <article v-html="blog.content">
                                </article>
                            </el-card>
                        </el-col>
                    </el-row>
                </el-main>
                <el-aside>
                    <div class="type" style="margin-left: 50px;">
                        <ul>
                            <li :class="{'active': activeIndex === '0'}" @click="handleSelect('0')"><span></span>全部</li>
                            <li v-for="(tag, index) in tags" :key="tag.blogTypeId"
                                :class="{'active': activeIndex === tag.blogTypeId.toString()}"
                                @click="handleSelect(tag.blogTypeId.toString())">
                                <span></span>{{ tag.typeName }}
                            </li>
                            <li :class="{'active': activeIndex === 'premium'}" @click="handleSelect('premium')"><span></span>精华</li>
                        </ul>
                    </div>
                    <div class="message">
                        <div class="logo">
                            <img src="/statics/images/logo.gif" alt="">
                        </div>
                        <div class="grid">
                            <div class="grid-item">
                                <p>分类数</p>
                                <span>{{tags.length}}</span>
                            </div>
                            <div class="grid-item">
                                <p>帖子数</p>
                                <span>{{blogs_count}}</span>
                            </div>
                            <div class="grid-item">
                                <p>浏览量</p>
                                <span>{{totalReaded}}</span>
                            </div>
                        </div>
                    </div>
                    <div class="follow" style="height: 500px">
                        <div id="followers">
                            <p>我关注的人</p>
                            <el-row>
                                <el-col :span="8" style="height:65px" v-for="follow in followers"
                                        :key="follow.userId" @click.native="userDetail(follow.userId)">
                                    <el-image style="width:40px;border-radius: 50%"
                                              :src="follow.avatar" fit="fill"></el-image>
                                    <div class="nickname">
                                        {{follow.nickname}}
                                        <i v-if="follow.isMutual == 1" class="el-icon-connection"></i>
                                    </div>
                                </el-col>
                            </el-row>
                            <div class="more">
                                <span @click="followerMore">更多...</span>
                            </div>
                        </div>
                        <div id="followed">
                            <p>关注我的人</p>
                            <el-row>
                                <el-col :span="8" style="height:65px" v-for="follow in followed"
                                        :key="follow.userId" @click.native="userDetail(follow.userId)">
                                    <el-image style="width:40px;height:40px;border-radius: 50%"
                                              :src="follow.avatar" fit="fill"></el-image>
                                    <div>
                                        {{follow.nickname}}
                                        <i v-if="follow.isMutual==1" class="el-icon-connection"></i>
                                    </div>
                                </el-col>
                            </el-row>
                            <div class="more">
                                <span @click="followedMore">更多...</span>
                            </div>
                        </div>
                    </div>
                </el-aside>
            </el-container>
        </el-main>
        <el-footer height="169px">
            &copy;copy right
        </el-footer>
    </el-container>
    <el-dialog :visible.sync="dialogVisible[0]"
               width="30%">
        <el-form ref="form" :model="form" label-width="160px"
                 :rules="rules">
            <el-form-item label="账号" prop="account" disabled>
                <el-input v-model="form.account" readOnly placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
                <el-input v-model="form.password" type="password" placeholder="请输入密码">
                </el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
                <el-input v-model="form.checkPassword" type="password" placeholder="请确认密码">
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit('form')">修改</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible[1]"
               width="30%">
        <el-form ref="newBlog" :model="newBlog" label-width="160px"
                 :rules="newBlogRules">
            <el-form-item label="标题" prop="title" disabled>
                <el-input v-model="newBlog.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="typeId">
                <el-select v-model="newBlog.typeId" placeholder="请选择博客类型">
                    <el-option v-for="tag in tags" :key="tag.blogTypeId" :label="tag.typeName"
                               :value="tag.blogTypeId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="正文" prop="content">
                <el-input v-model="newBlog.content"
                          minlength="10" type="textarea" placeholder="请输入正文">
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmitNew('newBlog')">发布</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</div>

</body>
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="/statics/js/request.js"></script>
<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                form: {
                    account: '',
                    password: '',
                    checkPassword: ''
                },
                rules: {
                    account: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
                    ],
                    checkPassword: [
                        {required: true, message: '请确认密码', trigger: 'blur'},
                        {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
                    ]
                },
                personInfo: {name: '张三', avatar: '/statics/images/logo.webp'}, //个人信息
                newBlog: {
                    title: '',
                    content: '',
                    typeId: null
                },
                newBlogRules: {
                    title: [
                        {required: true, message: '请输入博客标题', trigger: 'blur'},
                        {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '请输入正文', trigger: 'blur'},
                        {min: 10, max: 20000, message: '正文至少100字', trigger: 'blur'}
                    ],
                    typeId: [
                        {required: true, message: '请选择类型', trigger: 'blur'}
                    ]
                },
                blogs: [], //博客集合
                unload: 0,
                blogs_count: 0,
                totalReaded: 0,
                pageParam: {
                    current: 0,
                    size: 12,
                    totalSize: 1
                },
                tags: [],
                followers: [],   //关注者
                followed: [],   //被关注者
                activeIndex: '0', //默认导航菜单
                key: '',
                dialogVisible: [false, false], // 0是修改密码，1是新博客
            }
        },
        created() {
            //this.initBlog(this.pageParam)
            this.initType()
            this.initUser()
            this.initFollowers()
            this.initFolloweds()
            this.initBlog(this.pageParam);
            const token = window.sessionStorage.getItem('token');
            if (!token) {
                window.location = 'login';
            }
        },
        methods: {
            load() {
                if (this.pageParam.current * this.pageParam.size >= this.pageParam.totalSize) {
                    // 如果数据已经加载完毕，就不要再发请求了
                    return;
                }
                this.pageParam.current++; // 增加当前页数
                let data = {};
                // 如果是精华帖
                if (this.activeIndex === 'premium') {
                    data.isPremium = 1;
                } else {
                    data.typeId = this.activeIndex === '0' ? undefined : this.activeIndex;
                }
                data.key = this.key.trim() === '' ? undefined : this.key.trim();
                console.log('current:' + this.pageParam.current);
                this.initBlog(this.pageParam, data);
            },
            async initBlog(params, data) {
                let url = '/blogs';
                if (typeof data === "undefined") {
                    data = {};
                }
                await request.post(url, data, params, (res) => {
                    // 初始化博客列表
                    this.blogs = res.list;
                    if (this.unload == 0) {
                        // 计算总博客数
                        this.blogs_count = this.blogs.length;
                        // 计算总浏览量
                        this.totalReaded = this.blogs.reduce((sum, blog) => {
                            return sum + (blog.readed || 0); // 确保如果某个 blog.readed 为 undefined 或 null 时不出错
                        }, 0);
                        // 更新分页信息
                        this.pageParam.totalSize = res.totalSize;
                        this.pageParam.current = res.current;
                        this.unload = 1;
                    }
                });
            },
            async initType() {
                await request.post("/types", (res) => {
                    this.tags = res
                })
            },
            async initUser() {
                await request.post("/personalInfomation", (res) => {
                    this.personInfo = res
                    this.newBlog.author = res.userId
                    this.form.account = res.account
                })
            },
            async initFollowers() {
                await request.post("/followers", (res) => {
                    console.log(res)
                    this.followers = res
                })
            },
            async initFolloweds() {
                await request.post("/followeds", (res) => {
                    console.log(res)
                    this.followed = res
                })
            },
            search() {
                this.pageParam.current = 0
                this.blogs = []
                this.load()
            },
            handleSelect(index) {
                if (this.activeIndex === index) {
                    // 如果选中了相同的分类，避免重复加载
                    return;
                }

                this.pageParam.current = 0;  // 重置页数
                this.blogs = [];  // 清空当前数据

                // 根据选中的菜单项设置 activeIndex
                if (index === 'premium') {
                    this.activeIndex = 'premium';
                } else {
                    this.activeIndex = index;
                }

                this.load();  // 加载新的内容
            },
            blogDetail(id) {
                window.location = "/blog/" + id
            },
            followerMore() {
                window.location = "/users/followers"
            },
            followedMore() {
                window.location = "/users/followed"
            },
            userDetail(id) {
                console.log(id)
                window.location = "/personInfo/" + id
            },
            toggleStatus(status) {
                console.log(status)
                console.log(!this.dialogVisible)
                this.$set(this.dialogVisible, status, !this.dialogVisible[status])
            },
            logout() {
                window.sessionStorage.removeItem('token')
                document.cookie = undefined
                window.location = "/login"
            },
            toggleChangePassword() {
                this.toggleStatus(0)
            },
            toPersonInfo() {
                window.location = '/personInfo/' + this.personInfo.userId
            },
            menuClick(info) {
                this[info]()
            },
            onSubmit(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        request.post('/updatePassword', this.form, (res) => {
                            console.log("123")
                            window.sessionStorage.removeItem('token')
                            document.cookie = undefined
                            window.location = '/login'
                        })
                    } else {
                        this.$message("修改失败，请确认新密码！")
                    }
                })
            },
            onSubmitNew(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        this.newBlog.readed = 0
                        request.post("/addBlog", this.newBlog, (res) => {
                            if (res) {
                                this.$message("发布成功")
                                this.toggleStatus(1)
                            }
                        })
                    }
                })
            }
        },
        filters: {
            dateFormate(date) {
                return date.substring(0, 10)
            }
        }
    })
</script>
</html>